/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-02-23
 * Time: 10:21
 */
public class Sort {

    //归并排序
    //时间复杂度：O(n*log(n))
    //空间复杂度：O(1)
    //稳定性：稳定

    public static void mergeSort(int[] array) {
        mergeSortFunc(array,0,array.length-1);
    }

    private static void mergeSortFunc(int[] array,int left,int right) {
        if(left >= right) {
            return;
        }

        int mid = (left+right) / 2;

        mergeSortFunc(array,left,mid);
        mergeSortFunc(array,mid+1,right);
        merge(array,left,right,mid);

    }

    private static void merge(int[] array,int start,int end,int mid) {
        int s1 = start;
        int s2 = mid+1;

        int[] tmp = new int[end-start+1];
        int k = 0;

        while(s1 <= mid && s2 <= end) {
            if(array[s1] <= array[s2]) {
                tmp[k++] = array[s1++];
            }else {
                tmp[k++] = array[s2++];
            }
        }

        while(s1 <= mid) {
            tmp[k++] = array[s1++];
        }

        while(s2 <= end) {
            tmp[k++] = array[s2++];
        }

        for(int i = 0; i < tmp.length;i++) {
            array[i+start] = tmp[i];
        }

    }

    private static void swap(int[] array,int i,int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }


    //非递归实现
    public static void mergeSort1(int[] array) {
        int gap = 1;

        while(gap < array.length) {
            for (int i = 0; i < array.length; i += gap*2) {
                int left = i;
                int mid = left+gap-1; //有可能会越界
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                int right = mid+gap; //有可能会越界
                if(right >= array.length) {
                    right = array.length-1;
                }
                merge(array,left,right,mid);
            }
            gap *= 2;
        }
    }
}